package com.hq.fxh.No2_BBS.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hq.fxh.No2_BBS.Adapter.Radapter_PlateEditor;
import com.hq.fxh.Modle.EditorModle;
import com.hq.fxh.Modle.RequstReq;
import com.hq.fxh.Modle.UploadPlatModle;
import com.hq.fxh.R;
import com.hq.fxh.Utils.GlideUtils;
import com.hq.fxh.Utils.LogUtils;
import com.hq.fxh.Utils.SharedPreferenceUtils;
import com.hq.fxh.Utils.StatesBarUtils;
import com.hq.fxh.Utils.Tool;
import com.hq.fxh.Utils.UpLoadUtils;
import com.hq.fxh.HttpApi.UserServiceImpl;
import com.hq.fxh.CustomerView.PopupWindow.PopupForEditShare;
import com.hq.fxh.CustomerView.PopupWindow.PopupForEditZhiDing;
import com.hq.fxh.imageLoader.ImagePicker;
import com.hq.fxh.imageLoader.SelectPictureActivity;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class PlateEditorActivity extends TakePhotoActivity implements View.OnClickListener {

    protected TextView tvPlateEditorBack;
    protected TextView tvPlateEditorPublish;
    protected RecyclerView recyclePlateEditor;
    private ArrayList<EditorModle> datas = new ArrayList<>();
    private UploadPlatModle upPlatModle = new UploadPlatModle();
    ArrayList<UploadPlatModle.ContentBean> contentBeen;
    private Radapter_PlateEditor adapter;
    private TakePhoto takePhoto;
    EditText editText;
    boolean editStatus = false;
    int Ip = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plate_editor);
        StatesBarUtils.setWindowToWhite(this);

        initView();
        initData();
    }

    private void getEditorData() {
        ArrayList<UploadPlatModle.ContentBean> contentBeens = new ArrayList<>();

        for (int i = 0; i < datas.size(); i++) {
            EditorModle editorModle = datas.get(i);
            if (i == 0) {
           /*     upPlatModle.setZhiding_time(editorModle.getTimeCound());
                upPlatModle.setZhiding_tyle(editorModle.getTimeType());*/
                upPlatModle.setTitle(editorModle.getEditMessage());
                upPlatModle.setMember_id(SharedPreferenceUtils.getMemberId(this));
                upPlatModle.setCategory_first_id(editorModle.getCategory_first_id());
                upPlatModle.setCategory_second_id(editorModle.getCategory_second_id());
                upPlatModle.setCategory_first_name(editorModle.getCategory_first_Name());
                upPlatModle.setCategory_second_name(editorModle.getSelectPlateName());

            } else {
                UploadPlatModle.ContentBean contentBean = new UploadPlatModle.ContentBean();
                ArrayList<String> imageUrl = editorModle.getImageUrl();
                if (imageUrl == null) {
                    imageUrl = new ArrayList<>();
                }
                contentBean.setImgs(imageUrl);
                contentBean.setText(editorModle.getEditMessage());
                contentBean.setNum(i);
                contentBeens.add(contentBean);
            }
        }
        upPlatModle.setContent(contentBeens);
        Gson gson = new Gson();
        String s = gson.toJson(upPlatModle);
        LogUtils.e(s);
        upLoadPlate(s);


    }

    protected int getLayoutId() {
        return R.layout.activity_plate_editor;
    }


    public void initData() {


        datas.add(new EditorModle());
        datas.add(new EditorModle());
        recyclePlateEditor.setLayoutManager(new LinearLayoutManager(this));
        adapter = new Radapter_PlateEditor(PlateEditorActivity.this, datas);
        setListener();
        recyclePlateEditor.setAdapter(adapter);

    }

    private void setListener() {
        adapter.setEditCallBack(new Radapter_PlateEditor.EditCallBack() {
            /*
             * 选择版本
             * */
            @Override
            public void callSelectPlate(TextView textView, int position) {
                startActivityForResult(new Intent(PlateEditorActivity.this, PlateSelectActivity.class), 1001);
            }

            /*
             * 选择置顶属性
             * */
            @Override
            public void callSetZhiDing(TextView textView) {

                setZhiDingTime();

            }

            /*
            * 选择分享收费
            * */
            @Override
            public void callSetFenXian(TextView textView) {

                setZhiDingShareMoney();
            }

            /*
            * 选择图片
            * */
            @Override
            public void callSelectPic(GridView gridView, int position) {

                LogUtils.e("回掉，选择图片" + Ip);
                openPictureSeclect(position);
            }
            /*
            * 当输入框失去焦点时的回调
            * */

            @Override
            public void callEditorFocusChange(int position, String content) {
                LogUtils.e("回掉，callEditorFocusChange" + position);
                saveEditorContent(position, content);

            }
            /*
            * 增加编辑布局
            * */

            @Override
            public void callAddItem(int position) {

                LogUtils.e("回掉，callAddItem" + position);
                addEditorItem(position, new EditorModle());

            }

            /*
            * 移除编辑布局
            * */
            @Override
            public void callRemoveItem(int position) {
                LogUtils.e("回掉，callRemoveItem" + position);
                removeEidtorItem(position);
            }
            /*
            * 输入框得到焦点
            * */

            @Override
            public void callEditorGetFocus(int position, EditText editText) {
                getEditFocus(position, editText);
            }
            /*
            * 移除已经选择的图片
            * */

            @Override
            public void callRemovePic(int layoutPosition, int picPosition) {
                removePic(layoutPosition, picPosition);

            }
            /*
            * 标题输入框失去焦点监听
            * */

            @Override
            public void callTitleRemoveFocus(String data) {
                datas.get(0).setEditMessage(data);
            }

            @Override
            public void callTitleTitleChange(String data) {

                String editMessage = datas.get(0).getEditMessage() + "";

                if (data == null || editMessage.equals(data)) {

                } else {
                    datas.get(0).setEditMessage(data);
                }
            }
        });
    }

    private void removePic(int position, int picposition) {
        if (editStatus) {
            saveEditorContent(Ip, getStringFromEdit(editText));
        }
        Ip = position;

        String remove = datas.get(position).getImagePaths().remove(picposition);
        LogUtils.e("图片删除结果" + remove);
        refreshAdapter();

    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_PlateEditor_Back) {
            finish();

        } else if (view.getId() == R.id.tv_PlateEditor_Publish) {
            if (Tool.isFastClick()) {
                LogUtils.startToash(this, "发布中");
                if (editStatus) {
                    saveEditorContent(Ip, getStringFromEdit(editText));
                }
                filterData();
            }
        }
    }

    /*检查输入的数据是否符合标准*/
    private void filterData() {
        for (int i = 0; i < datas.size(); i++) {
            EditorModle editorModle = datas.get(i);
            if ((editorModle.getImagePaths() == null || editorModle.getImagePaths().size() == 0) && (editorModle.getEditMessage() == null || editorModle.equals(""))) {
                if (i == 0) {
                    LogUtils.startToash(this, "亲,您的题目为空");

                    return;

                } else {
                    LogUtils.startToash(this, "抱歉,您的第" + i + "条数据为空");
                }
                return;
            }
            if (i == 0) {
                int selectPlateName = editorModle.getCategory_second_id();
                if (selectPlateName == 0) {
                    LogUtils.startToash(this, "亲,请问你要在哪个版块发布？");
                    return;
                }

            }

        }

        upPic();
        dothing(1);
    }


    public void initView() {
        tvPlateEditorBack = (TextView) findViewById(R.id.tv_PlateEditor_Back);
        tvPlateEditorBack.setOnClickListener(PlateEditorActivity.this);
        tvPlateEditorPublish = (TextView) findViewById(R.id.tv_PlateEditor_Publish);
        tvPlateEditorPublish.setOnClickListener(PlateEditorActivity.this);
        recyclePlateEditor = (RecyclerView) findViewById(R.id.recycle_PlateEditor);
    }

    /* 增加图片*/
    public void addPic() {
        getCropOptions();
        getTakePhoto().onPickMultiple(3);
    }

    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    private void getCropOptions() {
        CompressConfig compressConfig = new CompressConfig.Builder().setMaxSize(100 * 1024).create();
        takePhoto.onEnableCompress(compressConfig, true);

    }


    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        LogUtils.e("获取图片成功");
        ArrayList<TImage> images = result.getImages();
        if (images != null) {
            ArrayList<String> strings = new ArrayList<>();
            for (int i = 0; i < images.size(); i++) {
                strings.add(images.get(i).getCompressPath());
            }
            datas.get(Ip).setImagePaths(strings);
            refreshAdapter();
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
        LogUtils.e("获取图片失败");

    }

    @Override
    public void takeCancel() {
        super.takeCancel();
        LogUtils.e("获取图片成取消");

    }

    /*设置置顶事件*/
    public void setZhiDingTime() {
        if (editStatus) {
            saveEditorContent(Ip, getStringFromEdit(editText));
        }
        Ip = 0;
        PopupForEditZhiDing popupForEditZhiDing = new PopupForEditZhiDing(PlateEditorActivity.this, new PopupForEditZhiDing.ZhiDingCallBack() {
            @Override
            public void call(String comment) {
                LogUtils.e(comment);
                switch (comment) {
                    case "时":
                        datas.get(0).setTimeType(1);
                        break;
                    case "天":
                        datas.get(0).setTimeType(2);

                        break;
                    case "月":
                        datas.get(0).setTimeType(3);

                        break;
                }

            }


            @Override
            public void Sure(int timeCound) {
                datas.get(0).setTimeCound(timeCound);
                refreshAdapter();

            }
        });

        popupForEditZhiDing.showAtLocation(recyclePlateEditor, Gravity.BOTTOM, 0, 0);
        Tool.setAlpha(this, 0.7f);
    }

    /*设置分享收费事件*/
    public void setZhiDingShareMoney() {
        if (editStatus) {
            saveEditorContent(Ip, getStringFromEdit(editText));
        }
        Ip = 0;
        PopupForEditShare popupForEditShare = new PopupForEditShare(PlateEditorActivity.this, new PopupForEditShare.ShareMoneyCallBack() {
            @Override
            public void callSure(String comment) {
                LogUtils.e(comment);
                datas.get(0).setShareMoney(Float.parseFloat(comment));
                refreshAdapter();

            }
        });

        popupForEditShare.showAtLocation(recyclePlateEditor, Gravity.BOTTOM, 0, 0);
        Tool.setAlpha(this, 0.7f);
    }

    public void openImageLoader() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideUtils());
        imagePicker.setMultiMode(true);
        imagePicker.setOutPutX(800);
        imagePicker.setOutPutY(800);
        imagePicker.setShowCamera(true);
        imagePicker.setSelectLimit(3);
        Intent intent = new Intent(PlateEditorActivity.this, SelectPictureActivity.class);
        startActivityForResult(intent, 100);

    }

    /* 图片选择事件响应*/
    private void openPictureSeclect(int position) {
        if (editStatus) {
            saveEditorContent(Ip, getStringFromEdit(editText));
        }

        Ip = position;
        addPic();
        refreshAdapter();
    }

    /*移除编辑框事件*/
    private void removeEidtorItem(int position) {
        if (editStatus) {
            saveEditorContent(Ip, getStringFromEdit(editText));
        }
        if (datas.size() <= 2) {
            LogUtils.startToash(this, "亲爱的，再删就什么都没有啦！");
            return;
        }
        Ip = position;
        datas.remove(position);
        refreshAdapter();
    }

    /*增加编辑框事件*/
    private void addEditorItem(int position, EditorModle addEditorModle) {
        if (editStatus) {
            saveEditorContent(Ip, getStringFromEdit(editText));
        }
        Ip = position;
        datas.add(position, addEditorModle);
        refreshAdapter();
    }

    /*保存用户输入的内容*/
    private void saveEditorContent(int position, String content) {
        if (editStatus) {
            editStatus = false;
            datas.get(position).setEditMessage(content);
        } else {

        }
    }

    /*输入框得到焦点事件*/
    private void getEditFocus(int position, EditText medit) {
        editStatus = true;
        editText = medit;
        Ip = position;

    }


    public String getStringFromEdit(EditText eddt) {
        if (Tool.editIsEmpty(eddt)) {
            return null;
        } else {
            return String.valueOf(eddt.getText());
        }

    }

    /*刷新编辑视图*/
    public void refreshAdapter() {
        adapter.setDatas(datas);
        adapter.notifyDataSetChanged();

    }

    UpLoadUtils upLoadUtils;
    UpLoadUtils.UpLoadPicCallBack upLoadPicCallBack;

    /*初始化图片上传工具*/
    private void upPic() {

        upLoadUtils = new UpLoadUtils();
        upLoadPicCallBack = new UpLoadUtils.UpLoadPicCallBack() {
            @Override
            public void onFinishCallBack(ArrayList<String> imageUrl, int tag) {
                LogUtils.e("finish的tag  :" + tag);

                if (imageUrl == null || imageUrl.size() == 0) {
                    LogUtils.e("finish内容为空");
                } else {
                    datas.get(tag).setImageUrl(imageUrl);
                    for (int i = 0; i < imageUrl.size(); i++) {
                        LogUtils.e(imageUrl.get(i));
                    }
                }
                if (tag + 1 < datas.size()) {
                    Message msg = new Message();
                    msg.what = 1001;
                    Bundle bundle = new Bundle();
                    bundle.putInt("tag", tag);
                    msg.setData(bundle);
                    handler.sendMessage(msg);
                } else {
                    LogUtils.e("图片上传结束");
                    getEditorData();
                }
            }

            @Override
            public void onErrorCallBack(int position, Throwable e) {

            }
        };
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1001:
                    Bundle data = msg.getData();
                    int tag = data.getInt("tag");
                    LogUtils.e("hand中的tag//" + tag);
                    tag = tag + 1;
                    LogUtils.e("hand中的tag+1//" + tag);
                    dothing(tag);
                    break;
            }
        }
    };

    public void dothing(int tag) {
        LogUtils.e("dothing中的tag//" + tag);
        if (tag >= datas.size()) {
            LogUtils.e("图片上传完毕");
            getEditorData();
            for (int i = 0; i < datas.size(); i++) {
                ArrayList<String> imageUrl = datas.get(i).getImageUrl();
                if (imageUrl != null && imageUrl.size() > 0) {
                    LogUtils.e(i + "数据" + imageUrl.toString());
                }
            }
        } else {
            ArrayList<String> imagePaths = datas.get(tag).getImagePaths();
            while (imagePaths == null || imagePaths.size() == 0) {
                LogUtils.e("第" + tag + "组图片为空");
                tag = tag + 1;
                if (tag >= datas.size()) {
                    LogUtils.e("图片上传完毕");
                    getEditorData();
                    return;
                } else {
                    imagePaths = datas.get(tag).getImagePaths();

                }
            }
            if (imagePaths != null && imagePaths.size() != 0) {
                upLoadUtils.startUpLoadPic(PlateEditorActivity.this, imagePaths, tag, upLoadPicCallBack);
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && data != null) {
            String firstName = data.getStringExtra("firstName");
            String secondName = data.getStringExtra("secondName");
            int firstID = data.getIntExtra("firstID", -1);
            int secondID = data.getIntExtra("secondID", -1);

            datas.get(0).setSelectPlateName(secondName);
            datas.get(0).setCategory_first_id(firstID);
            datas.get(0).setCategory_first_Name(firstName);
            datas.get(0).setCategory_second_id(secondID);

            LogUtils.e("firstId = " +firstID+" ,  firstName  ="+firstName+",  secondId = " +secondID+"  , secondName  ="+secondName);
            refreshAdapter();
        }
    }

    /* 上传文章*/
    public void upLoadPlate(String content) {
        LogUtils.e("请求参数-----" + content);
        UserServiceImpl.uploadPlate(content, new Callback<RequstReq>() {
            @Override
            public void onResponse(Call<RequstReq> call, Response<RequstReq> response) {
                try {
                    String msg = response.body().getMsg();
                    if (msg.equals("操作成功")) {
                        LogUtils.startToash(PlateEditorActivity.this, "发布成功");
                        finish();
                    } else {
                        LogUtils.startToash(PlateEditorActivity.this, msg);
                    }
                } catch (Exception e) {
                    LogUtils.e(e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<RequstReq> call, Throwable t) {
                LogUtils.e(t.getMessage());
            }
        });
    }


}
